package com.qijian.flowable.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qijian.common.utils.DateUtils;
import com.qijian.common.utils.StringUtils;
import com.qijian.flowable.domain.FlowableMatrixHuman;
import com.qijian.flowable.domain.vo.FlowableMatrixHumanVo;
import com.qijian.flowable.domain.vo.MatrixFieldVo;
import com.qijian.flowable.domain.vo.MatrixVo;
import com.qijian.flowable.mapper.FlowableMatrixHumanMapper;
import com.qijian.flowable.mapper.MatrixFieldMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.qijian.flowable.mapper.MatrixMapper;
import com.qijian.flowable.domain.Matrix;
import com.qijian.flowable.service.IMatrixService;

/**
 * 流程矩阵Service业务层处理
 *
 * @author qijian
 * @date 2022-02-08
 */
@Service
@RequiredArgsConstructor
public class MatrixServiceImpl extends ServiceImpl<MatrixMapper, Matrix> implements IMatrixService {

    private final MatrixMapper matrixMapper;

    private final FlowableMatrixHumanMapper flowableMatrixHumanMapper;

    private final MatrixFieldMapper matrixFieldMapper;


    @Override
    public List<MatrixVo> matrixListVo() {
        return matrixMapper.selectVoList();
    }

    //获得树级结构菜单
    @Override
    public List<FlowableMatrixHumanVo> treeListVo() throws IOException {

        List<FlowableMatrixHumanVo> list = flowableMatrixHumanMapper.selectVoList();
        //存储根节点
        List<FlowableMatrixHumanVo> rootList = new ArrayList<>();
        //遍历所有数据，找到根节点
        for (FlowableMatrixHumanVo vo: list) {
            if(vo.getParentId() == 0){
                //找到根节点的时候，寻找这个根节点下的子节点。
                findChildren(vo, list);
                //添加到根节点的列表中
                rootList.add(vo);
            }
        }
        return rootList;
    }

    private void findChildren(FlowableMatrixHumanVo root, List<FlowableMatrixHumanVo> voList){
        List<FlowableMatrixHumanVo> childrenList = new ArrayList<>();
        //遍历所有数据，找到是入参父节点的子节点的数据，然后加到childrenList集合中。
        for (FlowableMatrixHumanVo vo : voList) {
            if (root.getId().equals(vo.getParentId()))
                childrenList.add(vo);
        }
        //若子节点不存在，那么就不必再遍历子节点中的子节点了 直接返回。
        if(childrenList.size() == 0) {
            return;
        }
        //设置父节点的子节点列表
        root.setChildren(childrenList);
        //若子节点存在，递归调用，寻找子节点的子节点。
        for (FlowableMatrixHumanVo children : childrenList) {
            findChildren(children, voList);
        }
    }
}
